- 從上往下打印出二叉樹的每個節點,同層節點從左至右打印。
- 數據結構基本算法
vector<int> PrintFromTopToBottom(TreeNode* root) {
//層次遍歷二叉樹 需要隊列輔助
queue<TreeNode*> que;
vector<int> ans;
TreeNode* point;
que.push(root);
while(!que.empty())
{
point = que.front();
if(point != NULL) //非空節點
{
ans.push_back(point->val);
if(point->left!= NULL) //加入左樹
que.push(point->left);
if(point->right!= NULL) //加入右樹
que.push(point->right);
}
que.pop();
}
return ans;
}